package cn.rengy.web.framework.wxmp.message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.rengy.lang.ResultEntity;
import cn.rengy.web.framework.constants.Constants;

import cn.rengy.web.framework.securitycode.SecurityCodeService;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.wxmp.message.entity.TemplateMessage;

@Service
public class WxSecurityCodeService {
	@Autowired
	private DbService dbService;
	@Autowired
	private TemplateMessageService templateMessageService;
	@Autowired
	private SecurityCodeService securityCodeService;


	@Value("${wxmpAppid:null}")
	private String wxmpAppid;
	/**
	 * 发送微信登录验证码
	 * @return
	 */
	public ResultEntity sendSecurityCode(Map<String,Object> paramMap){
		String appid=wxmpAppid;
		String username=MapUtils.getString(paramMap,"username");
		//1.校验用户名是否存在
		String openid=this.dbService.querySingleColumn("select_get_openid_by_username", String.class, username,appid);
		if(StringUtils.isBlank(openid)){
			return ResultEntity.fail("用户名不存在");
		}
		//2.保存验证码
		ResultEntity<?,String> r=securityCodeService.save(Constants.KEY_WXSECURITYCODELOGIN, username);
		if(!r.isSuccess()) {
			return r;
		}
		String code=r.getData();//验证码
		//3.发送模板消息
		Map<String,String> dataMap=new HashMap<String,String>(1,1);
		dataMap.put("code", code);
		TemplateMessage templateMessage=new TemplateMessage();
		templateMessage.setAppid(appid);
		templateMessage.setData(dataMap);
		List<String> openidList=new ArrayList<String>(1);
		openidList.add(openid);
		templateMessage.setOpenidList(openidList);
		templateMessage.setTemplate_instance_id(WxMsgTemplateInstanceId.YZM);
		templateMessage.setUrl(null);
		try {
			templateMessageService.sendTemplateMessage(templateMessage);
		}catch(Exception e) {
			securityCodeService.evict(Constants.KEY_WXSECURITYCODELOGIN, username);
			return ResultEntity.fail("发送失败");
		}
		return ResultEntity.ok();
	}
	
}
